﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using CodeFormatter;

namespace SampleSite.Examples
{
    public partial class Examples : System.Web.UI.MasterPage
    {
        private string NameRoot = "TinyMCE Control > Examples";

        protected void Page_Load(object sender, EventArgs e)
        {
            string pageName = Utilities.AutoFileName(Request.Path);
            Page.Title = (String.IsNullOrEmpty(pageName)) ? NameRoot : NameRoot + " > " + pageName;
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (ExampleTitle.Controls.Count < 1)
                ExampleTitle.Controls.Add(new Literal() { Text = Utilities.AutoFileName(Request.Path) });            

            IEnumerable<HtmlControl> controls = Example.Controls.Cast<Control>().Where(c => c is HtmlControl).Cast<HtmlControl>().Where(h => h.TagName == "pre");
            string[] langs = new string[] { "html", "csharp", "vb", "js", "xml", "tsql", "msh" };
            foreach (HtmlControl item in controls)
            {
                if (item.Controls.Count == 1 && item.Controls[0] is LiteralControl)
                {
                    LiteralControl lit = (LiteralControl)item.Controls[0];
                    string[] classes = String.IsNullOrEmpty(item.Attributes["class"]) ? new string[0] : item.Attributes["class"].Split(' ');
                    var srcs = classes.Intersect(langs);
                    string lang = (srcs.Count() > 0) ? srcs.First() : "html";
                    if (lang == "csharp") lang = "c#";
                    HighlightOptions ho = new HighlightOptions() { AlternateLineNumbers = false, DisplayLineNumbers = true, Language=lang };
                    lit.Text = SourceFormatter.Highlight(ho, lit.Text);
                }
            }
        }
    }
}
